package com.archive.forum.service;

import com.archive.forum.dto.MessageDTO;
import com.archive.forum.dto.MessageSessionDTO;
import com.archive.forum.dto.UserDTO;
import com.archive.forum.mapper.*;
import com.archive.forum.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageSessionMapper messageSessionMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageExtMapper messageExtMapper;
    @Autowired
    private MessageSessionExtMapper messageSessionExtMapper;

    @Override
        public List<MessageSessionDTO> listSessions(Integer userId) {
        // 查询用户参与的所有会话
        MessageSessionExample example = new MessageSessionExample();
        example.or().andUser1IdEqualTo(userId);
        example.or().andUser2IdEqualTo(userId);
        example.setOrderByClause("gmt_modified DESC");
        List<MessageSession> sessions = messageSessionMapper.selectByExample(example);

        return sessions.stream().map(session -> {
            MessageSessionDTO dto = new MessageSessionDTO();
            dto.setId(session.getId());

            // 确定会话中的另一方用户
            Integer otherUserId = userId.equals(session.getUser1Id()) ?
                    session.getUser2Id() : session.getUser1Id();

            // 获取对方用户信息
            User otherUser = userMapper.selectByPrimaryKey(otherUserId);
            UserDTO userDTO = new UserDTO();
            userDTO.setId(otherUser.getId());
            userDTO.setNickname(otherUser.getNickname());
            userDTO.setAvatarUrl(otherUser.getAvatarUrl());
            dto.setOtherUser(userDTO);


            //从message表实时查询未读消息数
            dto.setUnreadCount(messageExtMapper.countUnreadMessagesInSession(
                    session.getId(), userId));

            return dto;
        }).collect(Collectors.toList());
    }

    @Transactional
    @Override
    public void sendMessage(Integer sessionId, Integer senderId, String content) {
        // 创建新消息
        Message message = new Message();
        message.setSessionId(sessionId);
        message.setSenderId(senderId);
        message.setContent(content);
        message.setGmtCreate(System.currentTimeMillis());
        messageMapper.insertSelective(message);

        // 更新会话的修改时间
        MessageSession session = new MessageSession();
        session.setId(sessionId);
        session.setGmtModified(System.currentTimeMillis());
        messageSessionMapper.updateByPrimaryKeySelective(session);
    }

    @Override
    public int getUnreadCount(Integer userId) {
        return messageExtMapper.countUnreadMessages(userId);
    }

    @Override
    public Integer findSessionId(Integer userId1, Integer userId2) {
        MessageSessionExample example = new MessageSessionExample();
        // 检查两种可能的用户ID顺序
        example.or().andUser1IdEqualTo(userId1).andUser2IdEqualTo(userId2);
        example.or().andUser1IdEqualTo(userId2).andUser2IdEqualTo(userId1);

        List<MessageSession> sessions = messageSessionMapper.selectByExample(example);
        return sessions.isEmpty() ? null : sessions.get(0).getId();
    }
    //添加会话
    @Transactional
    @Override
    public Integer createSession(Integer userId1, Integer userId2) {
        // 确保用户ID顺序一致，防止重复会话
        Integer user1Id = Math.min(userId1, userId2);
        Integer user2Id = Math.max(userId1, userId2);

        MessageSession session = new MessageSession();
        session.setUser1Id(user1Id);
        session.setUser2Id(user2Id);
        session.setGmtCreate(System.currentTimeMillis());
        session.setGmtModified(System.currentTimeMillis());

        messageSessionExtMapper.insertSelective(session);
        return session.getId();
    }
    @Override
    public MessageSession getSessionById(Integer sessionId) {
        return messageSessionMapper.selectByPrimaryKey(sessionId);
    }
    @Override
    public List<MessageDTO> listMessages(Integer sessionId,Integer currentUserId) {
        // 构建查询条件（按创建时间升序）
        MessageExample messageExample = new MessageExample();
        messageExample.createCriteria().andSessionIdEqualTo(sessionId);
        messageExample.setOrderByClause("gmt_create ASC");

        // 查询消息列表
        List<Message> messages = messageMapper.selectByExampleWithBLOBs(messageExample);

        return messages.stream().map(msg -> {
            MessageDTO dto = new MessageDTO();
            // 设置基础消息属性
            dto.setId(msg.getId());
            dto.setContent(msg.getContent());
            dto.setSenderId(msg.getSenderId());
            dto.setGmtCreate(msg.getGmtCreate());

            // 设置完整的发送者信息
            User sender = userMapper.selectByPrimaryKey(msg.getSenderId());
            if (sender != null) {
                UserDTO senderDTO = new UserDTO();
                senderDTO.setId(sender.getId());
                senderDTO.setNickname(sender.getNickname());
                senderDTO.setAvatarUrl(sender.getAvatarUrl());
                senderDTO.setBio(sender.getBio());
                senderDTO.setGmtCreate(sender.getGmtCreate());
                senderDTO.setGmtModified(sender.getGmtModified());
                if (!msg.getSenderId().equals(currentUserId) && !msg.getIsRead()) {
                    messageExtMapper.markAsRead(msg.getId());
                }
                dto.setSender(senderDTO);
            }

            return dto;
        }).collect(Collectors.toList());
    }
}